﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YJKRevitBase.WinForm;

namespace YJKRevitAxisModule
{
	public class GridsNumber
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public GridsNumber(ExternalCommandData cmdData)
		{
			this.m_cmdData = cmdData;
			if (GridsNumber._hWndRevit == null)
			{
                GridsNumber._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			string gridName = AxisNameManager.GetLargestNumber(cmdData.Application.ActiveUIDocument.Document).ToString();
			this.m_dlg = new GridsNumberForm(cmdData, gridName);
			this.m_dlg.Show(GridsNumber._hWndRevit);
			int wMsg = 7;
			GridsNumber.SendMessage(GridsNumber._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
		}

		public Result Run(ref string message)
		{
			Selection selection = this.m_cmdData.Application.ActiveUIDocument.Selection;
			RevitVersionFuncs.ClearSelection(selection);
			Result result;
			try
			{
				AxisFilter axisFilter = new AxisFilter();
				Reference reference = selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, axisFilter, "选择轴线");
				if (!AxisNameManager.IsValidatingOfName(this.m_dlg.GridNumber, true))
				{
					this.m_dlg.GridNumber = this.m_dlg.ValidGridName;
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
				else
				{
					this.m_cmdData.Application.ActiveUIDocument.Document.GetElement(reference).Name = this.m_dlg.GridNumber;
					this.m_cmdData.Application.ActiveUIDocument.Document.Regenerate();
					string nextLable = AxisNameManager.GetNextLable(this.m_dlg.GridNumber);
					List<string> allAxisLables = AxisNameManager.GetAllAxisLables(this.m_cmdData.Application.ActiveUIDocument.Document);
					while (allAxisLables.Contains(nextLable))
					{
						nextLable = AxisNameManager.GetNextLable(nextLable);
					}
					this.m_dlg.GridNumber = nextLable;
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
			}
			catch (Exception ex)
			{
				message = ex.Message;
				this.m_dlg.Close();
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

        public static WindowHandle _hWndRevit;

		protected ExternalCommandData m_cmdData;

		private GridsNumberForm m_dlg;
	}
}
